package com.nuoniu.sibanyun.config;

import com.nuoniu.sibanyun.service.ISysLogService;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 类说明: 全局日志记录.
 * @author 小啊刚
 * @date 2020/5/21
 */
@Aspect
@Component
public class GlobalLogConfig {

    @Autowired
    private ISysLogService sysLogService;

    @Pointcut("execution(* com.nuoniu.sibanyun.controller..*.*(..))")
    public void operationLog(){}

    /**
     * 环绕增强，相当于MethodInterceptor
     */
    @Around("operationLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object res = null;
        long time = System.currentTimeMillis();
        try {
            res =  joinPoint.proceed();
            time = System.currentTimeMillis() - time;
            return res;
        } finally {
            try {
                //方法执行完成后增加日志
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = attributes.getRequest();
                sysLogService.addOperationLog(joinPoint, res, time, request, UserThreadLocal.get());
            }catch (Exception e){
                System.out.println("LogAspect 操作失败：" + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    /*@Before("operationLog()")
    public void doBeforeAdvice(JoinPoint joinPoint){
        System.out.println("进入方法前执行.....");
    }*/

//    /**
//     * 处理完请求，返回内容
//     * @param ret
//     */
//    @AfterReturning(returning = "ret", pointcut = "operationLog()")
//    public void doAfterReturning(Object ret) {
//        System.out.println("方法的返回值 : " + ret);
//    }
}
